package com.atwisdom.star.core.bsl.functionClass.impl;

import com.atwisdom.star.common.util.FileUtil;
import com.atwisdom.star.common.vo.JsonResult;
import com.atwisdom.star.common.vo.ResultInfo;
import com.atwisdom.star.common.vo.StatusCode;
import com.atwisdom.star.core.bsl.functionClass.FileManageService;
import com.atwisdom.star.exception.pojo.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FileManageServiceImpl implements FileManageService {
    @Value("${filePath}")
    private String baseFilePath;

    @Override
    public ResultInfo<?> uploadFiles(MultipartFile[] files) throws BusinessException {
        try {
            List<Map<String, Object>> listMap = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                Map<String, Object> uploadMap = this.dealUploadFile(files[i]);
                listMap.add(uploadMap);
            }
            return JsonResult.success(listMap);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new BusinessException("999999", "上传文件失败！", ex);
        }
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 返回结果
     */
    @Override
    public ResultInfo<?> uploadFile(@RequestParam MultipartFile file) throws BusinessException {
        try {
            Map<String, Object> uploadMap = this.dealUploadFile(file);
            return JsonResult.success(uploadMap);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new BusinessException("999999", "上传文件失败！", ex);
        }
    }

    /**
     * 上传文件处理
     *
     * @param file 上传文件
     * @return 返回上文件信息
     */
    private Map<String, Object> dealUploadFile(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return null;
            }
            String fileName = file.getOriginalFilename();
            Date current = new Date();
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String strDate = simpleDate.format(current);
            String filePath = baseFilePath + strDate + "/";
            String path = filePath + fileName;
            File dest = new File(new File(path).getAbsolutePath());//
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            file.transferTo(dest);
            Map resultMap = new HashMap();
            resultMap.put("fileName", fileName);
            resultMap.put("newFileName", path);
            resultMap.put("originalFilename", file.getOriginalFilename());
            return resultMap;
        } catch (Exception ex) {
            throw new BusinessException("999999", "上传文件处理失败！", ex);
        }
    }

    /**
     * 小文件处理成Base64编码返回
     * @param param 文档参数
     * @return
     * @throws BusinessException
     */
    public ResultInfo<?> downloadFileBase64(Map<String, String> param) throws BusinessException {
        String path = param.get("path");
        String fileName = param.get("fileName");
        if (StringUtils.isNotBlank(path) && StringUtils.isNotBlank(fileName)) {
            String filePath = baseFilePath + path + "/" + fileName;
            String base64;
            InputStream in = null;
            try {
                File file = new File(filePath);
                in = new FileInputStream(file);
                byte[] bytes = new byte[(int) file.length()];
                in.read(bytes);
                base64 = Base64.getEncoder().encodeToString(bytes);
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("999999", "下载文件失败！", e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new BusinessException("999999", "下载文件失败！", e);
                    }
                }
            }
            return JsonResult.success(base64);
        }
        return JsonResult.error(StatusCode.ERROR_DOWNLOAD_FILE);
    }

    /**
     * 下载文件
     *
     * @param param 文档参数
     * @return
     * @throws BusinessException
     */
    @Override
    public void downloadFile(Map<String, String> param, HttpServletResponse response, HttpServletRequest request) throws BusinessException {
        String path = param.get("path");
        String fileName = param.get("fileName");
        try {
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = baseFilePath + path + "/" + fileName;
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtil.setAttachmentResponseHeader(response, realFileName);
            FileUtil.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            throw new BusinessException("999999", "下载文件失败！", e);
        }
    }


    @Override
    public ResultInfo<?> deleteFile(Map<String, String> param) throws BusinessException {
        String path = param.get("path");
        String fileName = param.get("fileName");
        path = baseFilePath + path + "/" + fileName;
        boolean deleteFlag  = FileUtil.deleteFile(path);
        if(deleteFlag){
            return JsonResult.success("文件删除成功");
        }else{
            return JsonResult.error(StatusCode.RUN_ERROR.getCode(),"文件删除失败");
        }
    }
}
